package com.wwl.cms.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.transaction.Transaction;

/**
 * @author wwl
 * @version 1.0
 * @date 2021/10/9 20:21
 * @description:
 */
@Api(value = "/redis",description = "Redis测试", tags = {"redis"})
@RestController
@RequestMapping(value = "/redis",produces = {"application/json"})
public class RedisController {
    @Autowired
    private RedisTemplate redisTemplate;
    @ApiOperation("Redis测试")
    @RequestMapping(value = "/testRedis", method = RequestMethod.POST)
    public String testRedis(){
        redisTemplate.opsForValue().set("name","wwl");
        return  (String) redisTemplate.opsForValue().get("name");
    }

    public String sale(){
        String qtKey = "product001";
        //添加乐观锁
        redisTemplate.watch(qtKey);
        //判断库存
        String qtkeyStr = redisTemplate.opsForValue().get(qtKey).toString();
        if (qtkeyStr==null||"".equals(qtkeyStr.trim())){
            return  "未初始化";
        }
        int qt = Integer.parseInt(qtkeyStr);
        if (qt<=0){
            return "已经秒光了";
        }
        //增加事务
         redisTemplate.multi();
        //减少库存
        redisTemplate.opsForValue().decrement(qtkeyStr);
        return null;

    }
}
